import { ref, getCurrentInstance, unref, nextTick, reactive, watch } from "vue";
import { DrawerInstance, Nullable, Fn ,DrawerProps} from "./type";
import { isFunction } from "@vue/shared";

const dataTransferRef = reactive<any>({});
export function useDrawer(props?: DrawerProps): any {
  if (!getCurrentInstance()) {
    throw new Error(
      "useDrawer() can only be used inside setup() or functional components!"
    );
  }
  const getInstance = () => {
    const instance = unref(drawerInstanceRef);
    if (!instance) {
      throw new Error("insatnce is undefined");
    }
    return instance;
  };

  const drawerInstanceRef = ref<Nullable<any>>(null);
  const loaded = ref(false);

  function register(DrawerInstance: DrawerInstance) {
    if (unref(loaded)) {
      return;
    }
    if (props) {
      DrawerInstance.setDrawerProps(props);
    }
    drawerInstanceRef.value = DrawerInstance;
    loaded.value = true;
  }

  function openDrawer(isOpen: boolean, params?: any) {
    getInstance()?.openDrawer(isOpen);
    dataTransferRef.value = params;
  }

  return [register, { openDrawer }];
}

export function useDrawerInner(callbackFn?: Fn): [any, () => void] {
  console.log(isFunction(callbackFn))
  if (!getCurrentInstance()) {
    throw new Error(
      "useDrawerInner() can only be used inside setup() or functional components!"
    );
  }

  const currentInstance = getCurrentInstance();

  const getInstance = () => {
    const instance = unref(drawerInstanceRef);
    if (!instance) {
      throw new Error("useDrawerInner instance is undefined!");
    }
    return instance;
  };

  watch(
    () => dataTransferRef.value,
    () => {
      const data = JSON.parse(JSON.stringify(dataTransferRef));
      if (!data) return;
      if (!callbackFn || !isFunction(callbackFn)) return;
      nextTick(() => {
        callbackFn(data.value);
      });
    },
    { deep: true }
  );

  const drawerInstanceRef = ref<Nullable<any>>(null);
  const loaded = ref(false);

  function register(modalInstance: DrawerInstance) {
    if (unref(loaded)) {
      return;
    }
    drawerInstanceRef.value = modalInstance;
    loaded.value = true;
    currentInstance?.emit("register", modalInstance);
  }

  function closeDrawer() {
    getInstance()?.openDrawer(false);
  }

  return [register, closeDrawer];
}
